from typing import List, Optional
from ..schemas.movie import MovieResponse, MovieRecommendation
from ..schemas.analytics import RatingDistribution, GenreDistribution
from ..utils.cache import cache
from ..core.config import settings

class MovieService:
    def __init__(self):
        # 模拟数据
        self.movies = [
            {
                "id": "1",
                "title": "肖申克的救赎",
                "director": "弗兰克·德拉邦特",
                "actors": ["蒂姆·罗宾斯", "摩根·弗里曼"],
                "genres": ["剧情", "犯罪"],
                "rating": 9.7,
                "votes": 2500000,
                "poster_url": "/static/images/shawshank.jpg",
                "release_date": "1994-09-23",
                "summary": "两个被囚禁的男人多年来建立了深厚的友谊，通过共同的希望找到了慰藉和最终的救赎。"
            },
            {
                "id": "2",
                "title": "别告诉她",
                "director": "王子逸",
                "actors": ["奥卡菲娜", "赵淑珍"],
                "genres": ["剧情", "家庭"],
                "rating": 8.6,
                "votes": 800000,
                "poster_url": "/static/images/farewell.jpg",
                "release_date": "2019-07-12",
                "summary": "一个中国家庭决定对奶奶隐瞒她的癌症诊断，并安排一场婚礼作为告别。"
            },
            {
                "id": "3",
                "title": "阿甘正传",
                "director": "罗伯特·泽米吉斯",
                "actors": ["汤姆·汉克斯", "罗宾·怀特"],
                "genres": ["剧情", "爱情"],
                "rating": 9.5,
                "votes": 2000000,
                "poster_url": "/static/images/forrest-gump.jpg",
                "release_date": "1994-07-06",
                "summary": "阿甘的一生充满了奇迹，他的纯真和善良影响着身边的每个人。"
            },
            {
                "id": "4",
                "title": "盗梦空间",
                "director": "克里斯托弗·诺兰",
                "actors": ["莱昂纳多·迪卡普里奥", "约瑟夫·高登-莱维特"],
                "genres": ["科幻", "动作", "悬疑"],
                "rating": 9.3,
                "votes": 1800000,
                "poster_url": "/static/images/inception.jpg",
                "release_date": "2010-07-16",
                "summary": "一位高超的盗梦者必须执行一项危险的任务：不是窃取而是植入思想。"
            },
            {
                "id": "5",
                "title": "千与千寻",
                "director": "宫崎骏",
                "actors": ["柊瑠美", "入野自由"],
                "genres": ["动画", "奇幻", "冒险"],
                "rating": 9.4,
                "votes": 1900000,
                "poster_url": "/static/images/spirited-away.jpg",
                "release_date": "2001-07-20",
                "summary": "小女孩千寻意外进入神灵世界，为了救回变成猪的父母，展开了一段奇妙的冒险。"
            },
            {
                "id": "6",
                "title": "星际穿越",
                "director": "克里斯托弗·诺兰",
                "actors": ["马修·麦康纳", "安妮·海瑟薇"],
                "genres": ["科幻", "冒险", "剧情"],
                "rating": 9.3,
                "votes": 1600000,
                "poster_url": "/static/images/interstellar.jpg",
                "release_date": "2014-11-07",
                "summary": "一组探险家通过新发现的虫洞展开一场跨越时空的旅程，寻找人类在宇宙中的新家园。"
            },
            {
                "id": "7",
                "title": "楚门的世界",
                "director": "彼得·威尔",
                "actors": ["金·凯瑞", "劳拉·琳妮"],
                "genres": ["剧情", "科幻"],
                "rating": 9.2,
                "votes": 1400000,
                "poster_url": "/static/images/truman-show.jpg",
                "release_date": "1998-06-05",
                "summary": "楚门不知道自己的生活是一场真人秀节目，直到他开始怀疑周围的世界。"
            },
            {
                "id": "8",
                "title": "寄生虫",
                "director": "奉俊昊",
                "actors": ["宋康昊", "赵汝贞"],
                "genres": ["剧情", "喜剧", "惊悚"],
                "rating": 9.1,
                "votes": 1300000,
                "poster_url": "/static/images/parasite.jpg",
                "release_date": "2019-05-30",
                "summary": "一个贫穷家庭通过各种手段逐渐侵入一个富裕家庭的生活，但事情开始失控。"
            },
            {
                "id": "9",
                "title": "疯狂动物城",
                "director": "拜伦·霍华德",
                "actors": ["金妮弗·古德温", "杰森·贝特曼"],
                "genres": ["动画", "冒险", "喜剧"],
                "rating": 9.2,
                "votes": 1500000,
                "poster_url": "/static/images/zootopia.jpg",
                "release_date": "2016-03-04",
                "summary": "兔子警官朱迪与狐狸尼克联手破案，揭开动物城背后的阴谋。"
            },
            {
                "id": "10",
                "title": "泰坦尼克号",
                "director": "詹姆斯·卡梅隆",
                "actors": ["莱昂纳多·迪卡普里奥", "凯特·温丝莱特"],
                "genres": ["爱情", "灾难", "剧情"],
                "rating": 9.4,
                "votes": 2100000,
                "poster_url": "/static/images/titanic.jpg",
                "release_date": "1997-12-19",
                "summary": "一段跨越阶级的爱情故事，发生在注定沉没的泰坦尼克号上。"
            },
            {
                "id": "11",
                "title": "大话西游之大圣娶亲",
                "director": "刘镇伟",
                "actors": ["周星驰", "朱茵"],
                "genres": ["喜剧", "爱情", "奇幻"],
                "rating": 9.2,
                "votes": 1700000,
                "poster_url": "/static/images/journey-west.jpg",
                "release_date": "1995-02-04",
                "summary": "至尊宝与紫霞仙子的爱情故事，穿越时空的仙侠喜剧。"
            },
            {
                "id": "12",
                "title": "黑客帝国",
                "director": "沃卓斯基姐妹",
                "actors": ["基努·里维斯", "劳伦斯·菲什伯恩"],
                "genres": ["科幻", "动作"],
                "rating": 9.0,
                "votes": 1400000,
                "poster_url": "/static/images/matrix.jpg",
                "release_date": "1999-03-31",
                "summary": "一位程序员发现现实世界是由机器创造的虚拟现实，并加入反抗军对抗机器统治。"
            },
            {
                "id": "13",
                "title": "让子弹飞",
                "director": "姜文",
                "actors": ["姜文", "周润发", "葛优"],
                "genres": ["剧情", "喜剧", "动作"],
                "rating": 9.0,
                "votes": 1300000,
                "poster_url": "/static/images/let-bullets-fly.jpg",
                "release_date": "2010-12-16",
                "summary": "一场发生在民国时期的高智商狙击战，充满了黑色幽默和寓意深刻的故事。"
            }
        ]

    @cache(expire_seconds=settings.CACHE_EXPIRE_TIME)
    def get_movie(self, movie_id: str) -> Optional[MovieResponse]:
        """获取电影详情"""
        for movie in self.movies:
            if movie["id"] == movie_id:
                return MovieResponse(**movie)
        return None

    @cache(expire_seconds=settings.CACHE_EXPIRE_TIME)
    def get_recommendations(self, movie_id: str, limit: int = 5) -> List[MovieRecommendation]:
        """获取电影推荐"""
        # 简单实现：返回除了指定电影之外的其他电影
        recommendations = []
        for movie in self.movies:
            if movie["id"] != movie_id:
                # 添加 similarity_score 字段
                movie_data = movie.copy()
                movie_data["similarity_score"] = 0.8  # 模拟相似度分数
                recommendations.append(MovieRecommendation(**movie_data))
            if len(recommendations) >= limit:
                break
        return recommendations

    @cache(expire_seconds=settings.CACHE_EXPIRE_TIME)
    def get_trending_movies(self, page: int = 1, page_size: int = 12) -> dict:
        """获取热门电影"""
        # 按评分和投票数排序
        sorted_movies = sorted(
            self.movies,
            key=lambda x: (x["rating"] * 0.7 + x["votes"] / 1000000 * 0.3),  # 评分权重0.7，投票数权重0.3
            reverse=True
        )
        
        # 计算分页
        start_idx = (page - 1) * page_size
        end_idx = start_idx + page_size
        paginated_movies = sorted_movies[start_idx:end_idx]
        
        return {
            "movies": [MovieResponse(**movie) for movie in paginated_movies],
            "total": len(sorted_movies),
            "has_more": end_idx < len(sorted_movies)
        }

    @cache(expire_seconds=settings.CACHE_EXPIRE_TIME)
    def get_rating_distribution(self) -> list[RatingDistribution]:
        """获取评分分布"""
        # 创建评分区间（8.0-10.0，步长0.5）
        rating_ranges = [round(i * 0.5 + 8.0, 1) for i in range(5)]
        distribution = []
        
        for rating in rating_ranges:
            count = len([m for m in self.movies if rating <= float(m["rating"]) < rating + 0.5])
            if count > 0:  # 只返回有电影的评分区间
                distribution.append(RatingDistribution(rating=rating, count=count))
        
        return distribution

    @cache(expire_seconds=settings.CACHE_EXPIRE_TIME)
    def get_genre_distribution(self) -> list[GenreDistribution]:
        """获取类型分布"""
        genre_stats = {}
        
        # 统计每个类型的电影数量和总评分
        for movie in self.movies:
            for genre in movie["genres"]:
                if genre not in genre_stats:
                    genre_stats[genre] = {"count": 0, "total_rating": 0}
                genre_stats[genre]["count"] += 1
                genre_stats[genre]["total_rating"] += float(movie["rating"])
        
        # 计算每个类型的平均评分并创建分布对象
        distribution = []
        for genre, stats in genre_stats.items():
            average_rating = round(stats["total_rating"] / stats["count"], 1)
            distribution.append(
                GenreDistribution(
                    genre=genre,
                    count=stats["count"],
                    average_rating=average_rating
                )
            )
        
        # 按电影数量降序排序
        return sorted(distribution, key=lambda x: x.count, reverse=True)
  